package com.hmall.user.listener;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.hmall.common.exception.CommonException;
import com.hmall.user.domain.po.User;
import com.hmall.user.service.IUserService;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class UserMqListener {

    @Autowired
    private IUserService userService;

    /**
     * 用户ID：用户密码：扣减钱
     * @param message
     */
    @RabbitListener(queues = "user.deduct.money.queue")
    public void handleMessage(String message){
        if(StrUtil.isNotBlank(message)) {
            List<String> list = StrUtil.split(message, ":");
            if(CollUtil.isNotEmpty(list) && list.size()==3){
                String id = list.get(0);
                String pw = list.get(1);
                String money = list.get(2);
                Long m = Long.valueOf(money);
                boolean flag = userService.lambdaUpdate()
                        .setSql("balance = balance - " + m)
                        .eq(User::getId, Long.valueOf(id))
                        .eq(User::getPassword, pw)
                        .update();
                if(!flag){
                    throw new CommonException("用户" + id + "扣减余额失败", 500);
                }
                //UPDATE `user` set balance = balance-? where id = ? and `password` = ?
            }
        }
    }


}
